﻿using CommonAsyncDemoFunctions;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace SimpleAsync
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		CancellationTokenSource tokensource = new CancellationTokenSource();
		public MainWindow()
		{
			InitializeComponent();
		}

		private async void StartClick(object sender, RoutedEventArgs e)
		{

			//Hanging Application, no cancellation
			//await FileLoader.ReloadFortunes();
			//FileLoader.ReloadFortunesSynchronous();
			//output.Text = "Fortunes Loaded: " + FileLoader.GetCount() + " Random Fortune: " + FileLoader.GetFortune();

			//Reponsive, cancellable long task in the UI
			try
			{
				await FileLoader.ReloadFortunesCancelable(tokensource).ContinueWith((t) =>
				{
					output.Text = "Fortunes Loaded: " + FileLoader.GetCount() 
											+ " Random Fortune: " + FileLoader.GetFortune();
				}, TaskScheduler.FromCurrentSynchronizationContext());
				//Note the use of the synchronization context above so that 
				//we can set the text value on the UI Control
			}
			catch (Exception ex)
			{
				output.Text = "Fortunes Loaded: " + FileLoader.GetCount() + "\n" + ex.Message;
				tokensource = new CancellationTokenSource();
			}
		}

		private void CancelClick(object sender, RoutedEventArgs e)
		{
			tokensource.Cancel();
		}
	}
}
